package controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import pojo.Book;
import service.BookService;
import tools.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2019/1/4.
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    BookService bookService;


    @RequestMapping("/list")
    public String getBookList(HttpServletRequest request, @RequestParam(value="chooseId",required = false)Integer chooseId,  @RequestParam(value="choose",required = false)String choose, Model model){
    String pageIndex=request.getParameter("pageIndex");
        try {
            int currPageNo = 1;

            if (pageIndex == "" || pageIndex == null) {
                currPageNo = 1;
            } else {
                currPageNo = Integer.parseInt(pageIndex);
            }
            Page pageObj = new Page();
            pageObj.setCurrPageNo(currPageNo);
            pageObj.setPageSize(2);
            pageObj = bookService.bookList(chooseId,choose,pageObj);
            model.addAttribute("page",pageObj);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";

    }

    @RequestMapping("/add")
    public String add(Book book,HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "pic_Path",required = false) MultipartFile attach){
        String idPicPath = null;
        //判断文件是否为空
        if(!attach.isEmpty()){
            String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");

            String oldFileName = attach.getOriginalFilename();//原文件名
            String prefix= FilenameUtils.getExtension(oldFileName);//原文件后缀
            int filesize = 500000;
            if(attach.getSize() >  filesize){//上传大小不得超过 500k
                request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
                return "addBook";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                String fileName = System.currentTimeMillis()+ RandomStringUtils.random(5, true, true)+"_Personal.jpg";
                File targetFile = new File(path, fileName);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "addBook";
                }
                idPicPath = path+File.separator+fileName;
            }else{
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "addBook";
            }
        }
        //book.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());

        book.setIdPicPath(idPicPath);
        if(bookService.add(book)>0){
            return "redirect:/book/list";
        }
        return "addBook";


    }

    @RequestMapping("/addBook")
    public String add(){
        return "addBook";
    }

    @RequestMapping("/update")
    public String updateBook(Book book,HttpServletResponse response){
        try {
            PrintWriter out = response.getWriter();
            int result = bookService.updateBook(book);
            if (result > 0) {
                out.print("<script type=\"text/javascript\">");
                out.print("alert(\"修改成功\");");
                out.print("</script>");
            }else{
                out.print("<script type=\"text/javascript\">");
                out.print("alert(\"修改失败\");");
                out.print("</script>");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/book/list";

    }

    @RequestMapping("/selectInfo")
    public String selectInfo(Model model,HttpServletRequest request){
        int id=Integer.parseInt(request.getParameter("bookId"));
        model.addAttribute("book",bookService.selectBookId(id));
        return "update";
    }

    @RequestMapping("/deleteInfo")
    public String deleteInfo(Model model,HttpServletRequest request){
        int id=Integer.parseInt(request.getParameter("bookId"));
        model.addAttribute("book",bookService.deleteById(id));
        return "redirect:/book/list";
    }

}
